package com.example.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.stereotype.Service;
import java.util.Map;


@Service
public class MqttSubscriptionManager {
    private final MqttPahoMessageDrivenChannelAdapter adapter;
    private static final Logger logger = LoggerFactory.getLogger(MqttSubscriptionManager.class);
    public MqttSubscriptionManager(MqttPahoMessageDrivenChannelAdapter adapter) {
        this.adapter = adapter;
    }

    public void subscribe(String topic, int qos) {
        logger.info("正在订阅主题: {} (QoS: {})", topic, qos);
        adapter.addTopic(topic, qos);
        if (!adapter.isRunning()) {
            //adapter.start();
            logger.info("MQTT未连接");
        }
    }

    public void unsubscribe(String topic) {
        adapter.removeTopic(topic);
    }

    public void subscribeAll(Map<String, Integer> topicQosMap) {
        topicQosMap.forEach((topic, qos) ->
                adapter.addTopic(topic, qos));
        if (!adapter.isRunning()) {
            adapter.start();
        }
    }
}